﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;
using com.lover.astd.common.manager;

namespace com.lover.astd.common.partner.impl
{
    public class KunlunLogin : LoginImplBase
    {
        public KunlunLogin() : base() { }
        public override bool alwaysNeedVerifyCode() { return true; }
        public override string getAlwaysCaptchaImageUrl() { return String.Format("http://login.kunlun.tw/?act=index.captcha&r={0}%27%20onerror=", _rand.NextDouble()); }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            if (verify_code == null)
            {
                buildAlwaysVerifyResult(ref result, ref cookies);
                return result;
            }

            string loginurl = "http://login.kunlun.tw/?act=user.weblogin&lang=tw";
            string data = String.Format("returl=http%3A%2F%2Fstatic.kunlun.tw%2Fwww%2Fsso_js_v2%2Fcallback.html&u=&u2=&username={0}&userpass={1}&usercode={2}",
                _username, _password, verify_code);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            //302
            string location = resp.getExtraHeader("Location");
            if (location == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            if (!location.Contains("retcode=0"))
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            // 获取设置cookie的url的请求
            string request_cook_url = "http://go.kunlun.tw/redirect2.php?ref=http://www.kunlun.tw/zh-tw/";
            resp = TransferMgr.doGetPure(request_cook_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            //302
            string get_cook_url = resp.getExtraHeader("Location");
            if (get_cook_url == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            resp = TransferMgr.doGetPure(get_cook_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            findingServerUrl();

            string gameurl = String.Format("http://s{0}.as.kimi.com.tw/root/start.action", _acc.ServerId);

            processStartGame(gameurl, result, ref cookies);
            return result;
        }
    }
}
